use std::path::PathBuf;

use color_eyre::eyre::{eyre, Result, WrapErr};
use directories::UserDirs;
use structopt::StructOpt;

use digital_garden::write;

/// A CLI for the growing and curation of a digital garden
///
/// Visit httt://www.xxx.com for more!
#[derive(Debug, StructOpt)]
#[structopt(name = "garden")]
struct Opt {
  //parse the path string
  #[structopt(parse(from_os_str), short = "p", long, env)]
  garden_path: Option<PathBuf>,

  #[structopt(subcommand)]
  cmd: Command,
}

#[derive(Debug, StructOpt)]
enum Command {
  /// write something in your garden
  ///
  /// This command will oen your $EDITOR, wait for your
  /// to write something, and then save the file to your
  /// garden
  Write {
    /// Optionally set a title for what you are going to
    #[structopt(short, long)]
    title: Option<String>,
  },
}

fn get_default_garden_dir() -> Result<PathBuf> {
  let user_dirs = UserDirs::new().ok_or_else(|| {
    eyre!("Could not get home directory. Are you sure you are on a computer?")
  })?;
  Ok(user_dirs.home_dir().join(".garden"))
  // return Err(eyre!("here")); // cargo run -- write 即 garden write
}

fn main() -> Result<()> {
  color_eyre::install()?;
  let opt = Opt::from_args();
  dbg!(&opt);

  // GARDEN_PATH=xxxpath/xxx cargo run -- write
  let garden_path = match opt.garden_path {
    Some(pathbuf) => Ok(pathbuf),
    None => get_default_garden_dir().wrap_err("`garden_path` was not supplied"),
  }?;

  match opt.cmd {
    Command::Write { title } => write(garden_path, title),
  }
}
